package com.linksfield.topup.interceptor;


import com.linksfield.topup.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录拦截器
 *
 * @author: lm
 * @date: 2019-11-21 15:40
 */
public class LoginInterceptor implements HandlerInterceptor {

    private static Logger logger = Logger.getLogger(LoginInterceptor.class);

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        //2020-07-01 代码中做了一些调整：x-access-token的验证我们不在拦截器里面完成，验证全部都交由本身的代码来验证

        boolean flag = false;

        try {
            if (null != request) {

                if (StringUtils.isBlank(request.getHeader("x-access-token"))) {
                    //如果拦截器本身验证就返回flag = false;flag = true的返回方式就是把验证权交给外部的代码
                    //flag = false;
                    flag = true;
                } else {
                    String token = request.getHeader("x-access-token");
                    if (null == JwtUtil.parseJWT(token)) {
                        //如果拦截器本身验证就返回flag = false;flag = true的返回方式就是把验证权交给外部的代码
                        //flag = false;
                        flag = true;

                    } else {
                        //解析token
                        Claims claims = JwtUtil.parseJWT(token);
                        String userName = claims.get("userName") + "";
                        int id = Integer.parseInt(claims.get("id") + "");
                        //可以调用用户管理的Service，根据用户名和ID来判断当前token提交的用户是否合法
                        //不合法则flag=false
                        if (StringUtils.isNoneBlank(userName)) {
                            flag = true;
                        }
                    }
                }
            } else {
                //如果这这边拦截器直接返回false的话，那最终的请求就到达不了代码，无法控制返回
                //flag = false;
                flag = true;
            }

        } catch (Exception e) {
            logger.info("解析x-access-token出现异常" + e);
            flag = false;
        }

        return flag;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
            throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
